package com.ecoolex.ying.space.core.manager;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ecoolex.framework.common.enums.ResultCode;
import com.ecoolex.framework.common.pojo.Page;
import com.ecoolex.framework.common.pojo.Pagination;
import com.ecoolex.framework.common.pojo.Sorting;
import com.ecoolex.framework.common.pojo.Sortings;
import com.ecoolex.framework.common.util.BizAssert;
import com.ecoolex.framework.common.util.Check;
import com.ecoolex.framework.modularize.api.service.storage.StorageService;
import com.ecoolex.framework.modularize.api.service.storage.UploadSource;
import com.ecoolex.ying.space.core.dao.UserWorksDAO;
import com.ecoolex.ying.space.entity.UserWorks;
import com.ecoolex.ying.space.entity.UserWorks.Column;
import com.ecoolex.ying.space.entity.UserWorksExample;
import com.ecoolex.ying.space.entity.UserWorksExample.Criteria;
import com.ecoolex.ying.space.entity.UserWorksImages;
import com.ecoolex.ying.space.entity.UserWorksOpus;
import com.ecoolex.ying.space.entity.UserWorksOpusItems;
import com.ecoolex.ying.space.entity.UserWorksShopping;
import com.ecoolex.ying.space.entity.UserWorksVideo;
import com.ecoolex.ying.space.enums.UserWorksAuditStatus;
import com.ecoolex.ying.space.enums.UserWorksStatus;
import com.ecoolex.ying.space.enums.UserWorksType;
import com.ecoolex.ying.space.pojo.AddUserWorksDTO;
import com.ecoolex.ying.space.pojo.AddUserWorksImageDTO;
import com.ecoolex.ying.space.pojo.AddUserWorksImagesDTO;
import com.ecoolex.ying.space.pojo.AddUserWorksOpusDTO;
import com.ecoolex.ying.space.pojo.AddUserWorksShoppingsDTO;
import com.ecoolex.ying.space.pojo.AddUserWorksVideoDTO;
import com.ecoolex.ying.space.pojo.EditUserWorksImageDTO;
import com.ecoolex.ying.space.pojo.EditUserWorksOpusDTO;
import com.ecoolex.ying.space.pojo.EditUserWorksVideoDTO;
import com.google.common.collect.Lists;

import static com.ecoolex.ying.space.entity.UserWorks.NOT_DELETED;


@Service
public class UserWorksManager {

    @Autowired
    private UserWorksDAO dao;

    @Autowired
    private UserWorksImagesManager userWorksImagesManager;

    @Autowired
    private UserWorksVideoManager userWorksVideoManager;

    @Autowired
    private UserWorksOpusManager userWorksOpusManager;

    @Autowired
    private UserWorksStatisticalManager userWorksStatisticalManager;

    @Autowired
    private StorageService storageService;

    @Autowired
    private UserWorksAuditManager userWorksAuditManager;

    @Autowired
    private UserWorksOpusItemsManager userWorksOpusItemsManager;

    @Autowired
    private UserWorksShoppingManager userWorksShoppingManager;

    @Autowired
    private ShareImageManager shareImageManager;

    public void verify(AddUserWorksDTO record) {
        BizAssert.isTrue(Check.notNullOrTrimEmpty(record.getTitle()), ResultCode.VERIFY.build(10), "作品标题为空");
        BizAssert.isTrue(Check.notNullOrTrimEmpty(record.getCoverImage()), ResultCode.VERIFY.build(11), "作品封面图为空");
    }

    public UserWorks getById(Integer worksId) {
        return dao.selectByPrimaryKey(worksId);
    }

    public UserWorks getByIdForH5(Integer worksId) {
        UserWorksExample example = new UserWorksExample();
        Criteria criteria = example.createCriteria();
        criteria.andWorksIdEqualTo(worksId).andAuditStatusEqualTo(UserWorksAuditStatus.PASS.real()).andStatusEqualTo(
                UserWorksStatus.RELEASE.real()).andDeletedEqualTo(NOT_DELETED);
        return dao.selectOneByExample(example);
    }

    public UserWorks getByIdAndUserId(Integer worksId, Integer userId) {
        UserWorksExample example = new UserWorksExample();
        Criteria criteria = example.createCriteria();
        criteria.andWorksIdEqualTo(worksId).andUserIdEqualTo(userId).andDeletedEqualTo(NOT_DELETED);
        return dao.selectOneByExample(example);
    }

    /**
     * 首页作品推荐列表
     *
     * @param title
     * @param worksType
     * @param sorts
     * @param page
     * @return
     */
    public Pagination<UserWorks> queryForH5(String title, Integer worksType, Date now, Sorting[] sorts, Page page) {
        UserWorksExample example = new UserWorksExample();
        Criteria criteria = example.createCriteria();
        if (Check.notNullOrTrimEmpty(title)) {
            criteria.andTitleLike("%" + title
                    + "%");
        }
        if (Check.notNullAndGtZero(worksType)) {
            criteria.andWorksTypeEqualTo(worksType);
        }
        criteria.andCreateTimeLessThanOrEqualTo(now).andAuditStatusEqualTo(
                UserWorksAuditStatus.PASS.real()).andStatusEqualTo(UserWorksStatus.RELEASE.real()).andDeletedEqualTo(
                NOT_DELETED);
        example.orderBy(Sortings.builder(sorts).verify(Column::valueOf).toSql());
        example.setOffset(page.getFirstIndex());
        example.setRows(page.getPageSize());

        return Pagination.create(page, dao.countByExample(example), () -> dao.selectByExample(example));
    }

    /**
     * 首页作品关注列表
     *
     * @param title
     * @param worksType
     * @param sorts
     * @param page
     * @return
     */
    public Pagination<UserWorks> queryWatchForH5(Integer userId, String title, Integer worksType, Date now, Sorting[] sorts, Page page) {

        return Pagination.create(page,
                dao.countByWatch(userId, title, worksType, now),
                dao.queryByWatch(userId,
                        title,
                        worksType,
                        now,
                        Sortings.builder(sorts).verify(Column::valueOf).toSql(),
                        page));
    }

    /**
     * 查询我的发布作品
     *
     * @param title
     * @param userId
     * @param sorts
     * @param page
     * @return
     */
    public Pagination<UserWorks> queryMyUserWorksOpusForH5(String title, Integer worksType, Integer userId, Sorting[] sorts, Page page) {
        UserWorksExample example = new UserWorksExample();
        Criteria criteria = example.createCriteria();
        if (Check.notNullOrTrimEmpty(title)) {
            criteria.andTitleLike("%" + title
                    + "%");
        }
        if (Check.notNullAndGtZero(worksType)) {
            criteria.andWorksTypeEqualTo(worksType);
        }
        criteria.andUserIdEqualTo(userId).andDeletedEqualTo(NOT_DELETED);
        example.orderBy(Sortings.builder(sorts).verify(Column::valueOf).toSql());
        example.setOffset(page.getFirstIndex());
        example.setRows(page.getPageSize());

        return Pagination.create(page, dao.countByExample(example), () -> dao.selectByExample(example));
    }

    /**
     * 查询我的发布灵感
     *
     * @param title
     * @param userId
     * @param sorts
     * @param page
     * @return
     */
    public Pagination<UserWorks> queryMyUserWorksForH5(String title, Integer userId, Sorting[] sorts, Page page) {
        UserWorksExample example = new UserWorksExample();
        Criteria criteria = example.createCriteria();
        if (Check.notNullOrTrimEmpty(title)) {
            criteria.andTitleLike("%" + title
                    + "%");
        }
        criteria.andUserIdEqualTo(userId).andDeletedEqualTo(NOT_DELETED).andWorksTypeEqualTo(
                UserWorksType.IMAGES.real());
        Criteria criteria2 = example.createCriteria();
        if (Check.notNullOrTrimEmpty(title)) {
            criteria2.andTitleLike("%" + title
                    + "%");
        }
        criteria2.andUserIdEqualTo(userId).andDeletedEqualTo(NOT_DELETED).andWorksTypeEqualTo(
                UserWorksType.VIDEO.real());
        example.or(criteria2);
        example.orderBy(Sortings.builder(sorts).verify(Column::valueOf).toSql());
        example.setOffset(page.getFirstIndex());
        example.setRows(page.getPageSize());

        return Pagination.create(page, dao.countByExample(example), () -> dao.selectByExample(example));
    }

    public long queryMyUserWorksCountOpusForH5(Integer worksType, Integer userId) {
        UserWorksExample example = new UserWorksExample();
        Criteria criteria = example.createCriteria();
        if (Check.notNullAndGtZero(worksType)) {
            criteria.andWorksTypeEqualTo(worksType);
        }
        criteria.andUserIdEqualTo(userId).andDeletedEqualTo(NOT_DELETED);
        return dao.countByExample(example);
    }

    public long queryMyUserWorksCountForH5(Integer userId) {
        UserWorksExample example = new UserWorksExample();
        Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId).andWorksTypeEqualTo(UserWorksType.IMAGES.real()).andDeletedEqualTo(
                NOT_DELETED);
        Criteria criteria2 = example.createCriteria();
        criteria2.andUserIdEqualTo(userId).andWorksTypeEqualTo(UserWorksType.VIDEO.real()).andDeletedEqualTo(
                NOT_DELETED);
        example.or(criteria2);
        return dao.countByExample(example);
    }

    /**
     * 查询他人发布作品
     *
     * @param title
     * @param userId
     * @param sorts
     * @param page
     * @return
     */
    public Pagination<UserWorks> queryOtherUserWorksOpusForH5(String title, Integer userId, Sorting[] sorts, Page page) {
        UserWorksExample example = new UserWorksExample();
        Criteria criteria = example.createCriteria();
        if (Check.notNullOrTrimEmpty(title)) {
            criteria.andTitleLike("%" + title
                    + "%");
        }
        criteria.andUserIdEqualTo(userId).andWorksTypeEqualTo(UserWorksType.OPUS.real()).andAuditStatusEqualTo(
                UserWorksAuditStatus.PASS.real()).andStatusEqualTo(UserWorksStatus.RELEASE.real()).andDeletedEqualTo(
                NOT_DELETED);
        example.orderBy(Sortings.builder(sorts).verify(Column::valueOf).toSql());
        example.setOffset(page.getFirstIndex());
        example.setRows(page.getPageSize());

        return Pagination.create(page, dao.countByExample(example), () -> dao.selectByExample(example));
    }

    /**
     * 查询他人发布灵感
     *
     * @param title
     * @param userId
     * @param sorts
     * @param page
     * @return
     */
    public Pagination<UserWorks> queryOtherUserWorksForH5(String title, Integer userId, Sorting[] sorts, Page page) {
        UserWorksExample example = new UserWorksExample();
        Criteria criteria = example.createCriteria();
        if (Check.notNullOrTrimEmpty(title)) {
            criteria.andTitleLike("%" + title
                    + "%");
        }
        criteria.andUserIdEqualTo(userId).andWorksTypeEqualTo(UserWorksType.IMAGES.real()).andAuditStatusEqualTo(
                UserWorksAuditStatus.PASS.real()).andStatusEqualTo(UserWorksStatus.RELEASE.real()).andDeletedEqualTo(
                NOT_DELETED);

        Criteria criteria2 = example.createCriteria();
        if (Check.notNullOrTrimEmpty(title)) {
            criteria2.andTitleLike("%" + title
                    + "%");
        }
        criteria2.andUserIdEqualTo(userId).andWorksTypeEqualTo(UserWorksType.VIDEO.real()).andAuditStatusEqualTo(
                UserWorksAuditStatus.PASS.real()).andStatusEqualTo(UserWorksStatus.RELEASE.real()).andDeletedEqualTo(
                NOT_DELETED);
        example.or(criteria2);
        example.orderBy(Sortings.builder(sorts).verify(Column::valueOf).toSql());
        example.setOffset(page.getFirstIndex());
        example.setRows(page.getPageSize());

        return Pagination.create(page, dao.countByExample(example), () -> dao.selectByExample(example));
    }

    public long queryOtherUserWorksOpusCountForH5(Integer userId) {
        UserWorksExample example = new UserWorksExample();
        Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId).andWorksTypeEqualTo(UserWorksType.OPUS.real()).andAuditStatusEqualTo(
                UserWorksAuditStatus.PASS.real()).andStatusEqualTo(UserWorksStatus.RELEASE.real()).andDeletedEqualTo(
                NOT_DELETED);
        return dao.countByExample(example);
    }

    public long queryOtherUserWorksCountForH5(Integer userId) {
        UserWorksExample example = new UserWorksExample();
        Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId).andWorksTypeEqualTo(UserWorksType.IMAGES.real()).andAuditStatusEqualTo(
                UserWorksAuditStatus.PASS.real()).andStatusEqualTo(UserWorksStatus.RELEASE.real()).andDeletedEqualTo(
                NOT_DELETED);

        Criteria criteria2 = example.createCriteria();
        criteria2.andUserIdEqualTo(userId).andWorksTypeEqualTo(UserWorksType.VIDEO.real()).andAuditStatusEqualTo(
                UserWorksAuditStatus.PASS.real()).andStatusEqualTo(UserWorksStatus.RELEASE.real()).andDeletedEqualTo(
                NOT_DELETED);
        example.or(criteria2);
        return dao.countByExample(example);
    }

    /**
     * 查询灵感辑列表（图文+视频）
     *
     * @param title
     * @param auditStatus
     * @param sorts
     * @param page
     * @return
     */
    public Pagination<UserWorks> queryUserWorksList(String title, Integer auditStatus, Sorting[] sorts, Page page) {
        UserWorksExample example = new UserWorksExample();
        Criteria criteria = example.createCriteria();
        if (Check.notNullOrTrimEmpty(title)) {
            criteria.andTitleLike("%" + title
                    + "%");
        }
        if (Check.notNullAndGteZero(auditStatus)) {
            criteria.andAuditStatusEqualTo(auditStatus);
        }
        List<Integer> list = new ArrayList<Integer>();
        list.add(UserWorksType.IMAGES.real());
        list.add(UserWorksType.VIDEO.real());
        criteria.andWorksTypeIn(list).andDeletedEqualTo(NOT_DELETED);
        example.orderBy(Sortings.builder(sorts).verify(Column::valueOf).toSql());
        example.setOffset(page.getFirstIndex());
        example.setRows(page.getPageSize());

        return Pagination.create(page, dao.countByExample(example), () -> dao.selectByExample(example));
    }

    /**
     * 查询作品列表
     *
     * @param title
     * @param auditStatus
     * @param sorts
     * @param page
     * @return
     */
    public Pagination<UserWorks> queryUserWorksOpusList(String title, Integer auditStatus, Sorting[] sorts, Page page) {
        UserWorksExample example = new UserWorksExample();
        Criteria criteria = example.createCriteria();
        if (Check.notNullOrTrimEmpty(title)) {
            criteria.andTitleLike("%" + title
                    + "%");
        }
        if (Check.notNullAndGteZero(auditStatus)) {
            criteria.andAuditStatusEqualTo(auditStatus);
        }
        criteria.andWorksTypeEqualTo(UserWorksType.OPUS.real()).andDeletedEqualTo(NOT_DELETED);
        example.orderBy(Sortings.builder(sorts).verify(Column::valueOf).toSql());
        example.setOffset(page.getFirstIndex());
        example.setRows(page.getPageSize());

        return Pagination.create(page, dao.countByExample(example), () -> dao.selectByExample(example));
    }

    /**
     * 我的橱窗-内容列表
     *
     * @param title
     * @param worksType
     * @param userId
     * @param sorts
     * @param page
     * @return
     */
    public Pagination<UserWorks> queryMyShopWindowUserWorks(String title, Integer worksType, Integer userId, Sorting[] sorts, Page page) {

        return Pagination.create(page,
                dao.countByUserWorksShopping(userId, title, worksType),
                () -> dao.queryByUserWorksShopping(userId,
                        title,
                        worksType,
                        Sortings.builder(sorts).verify(Column::valueOf).toSql(),
                        page));
    }

    /**
     * 添加图文灵感辑
     *
     * @param addUserWorksImageDTO
     * @param userId
     * @param createUser
     * @return
     */
    @Transactional
    public UserWorks addUserWorksImages(AddUserWorksImageDTO addUserWorksImageDTO, Integer userId, String createUser) {
        BizAssert.isTrue(Check.notNullOrTrimEmpty(addUserWorksImageDTO.getTitle()),
                ResultCode.VERIFY.build(10),
                "灵感辑标题为空");
        BizAssert.isTrue(Check.notNullOrTrimEmpty(addUserWorksImageDTO.getContent()),
                ResultCode.VERIFY.build(11),
                "灵感辑内容为空");
        BizAssert.isTrue(Check.notNullOrEmpty(addUserWorksImageDTO.getAddUserWorksImagesDTOList()),
                ResultCode.VERIFY.build(12),
                "图片列表为空");

        UserWorks userWorks = new UserWorks();
        userWorks.setCoverImage(addUserWorksImageDTO.getAddUserWorksImagesDTOList().get(0).getStorageId());
        userWorks.setTitle(addUserWorksImageDTO.getTitle());
        userWorks.setWorksType(UserWorksType.IMAGES.real());
        userWorks.setUserId(userId);
        userWorks.setStatus(UserWorksStatus.RELEASE.real());
        userWorks.setAuditRecordId(0);
        userWorks.setAuditStatus(UserWorksAuditStatus.WAITAUDIT.real());
        userWorks.setDeleted(NOT_DELETED);
        userWorks.setCreateUser(createUser);
        userWorks.setCreateTime(Date.from(Instant.now()));
        userWorks.setUpdateUser(createUser);
        userWorks.setUpdateTime(Date.from(Instant.now()));

        dao.insert(userWorks);
        // 添加分享图片
        shareImageManager.addShareImage(userWorks.getCoverImage());
        // 添加图文作品
        UserWorksImages userWorksImages
                = userWorksImagesManager.createUserWorksImages(userWorks, addUserWorksImageDTO, createUser);
        // 添加标签
        List<UserWorksShopping> shoppingList = Lists.newArrayList();

        List<AddUserWorksImagesDTO> addUserWorksImagesDTOList = addUserWorksImageDTO.getAddUserWorksImagesDTOList();
        for (AddUserWorksImagesDTO addUserWorksImagesDTO : addUserWorksImagesDTOList) {
            // 获取图片标签购物列表
            List<AddUserWorksShoppingsDTO> addUserWorksShoppingsDTOList
                    = addUserWorksImagesDTO.getAddUserWorksShoppingsDTOList();
            // 添加购物标签
            List<UserWorksShopping> result = userWorksShoppingManager.updateUserWorksShopping(userWorks,
                    addUserWorksImagesDTO.getStorageId(),
                    addUserWorksShoppingsDTOList,
                    createUser);
            shoppingList.addAll(result);
        }
        // 创建作品计数基础数据
        userWorksStatisticalManager.add(userWorks.getWorksId(), createUser);
        // 审核申请
        userWorksAuditManager.applyImages(userWorks, userWorksImages, shoppingList);
        return userWorks;
    }

    /**
     * 添加视频灵感辑
     *
     * @param addUserWorksVideoDTO
     * @param userId
     * @param createUser
     * @return
     */
    @Transactional
    public UserWorks addUserWorksVideo(AddUserWorksVideoDTO addUserWorksVideoDTO, Integer userId, String createUser) {
        BizAssert.isTrue(Check.notNullOrTrimEmpty(addUserWorksVideoDTO.getTitle()),
                ResultCode.VERIFY.build(10),
                "灵感辑标题为空");
        BizAssert.isTrue(Check.notNullOrTrimEmpty(addUserWorksVideoDTO.getContent()),
                ResultCode.VERIFY.build(11),
                "灵感辑内容为空");
        BizAssert.isTrue(Check.notNullOrTrimEmpty(addUserWorksVideoDTO.getStorageId()),
                ResultCode.VERIFY.build(12),
                "视频资源id为空");
        BizAssert.isTrue(storageService.checkSource(new UploadSource("UserWorksVideo", "Video"),
                addUserWorksVideoDTO.getStorageId()), ResultCode.VERIFY.build(13), "视频资源id无效");

        UserWorks userWorks = new UserWorks();
        userWorks.setCoverImage(addUserWorksVideoDTO.getStorageId());
        userWorks.setTitle(addUserWorksVideoDTO.getTitle());
        userWorks.setWorksType(UserWorksType.VIDEO.real());
        userWorks.setUserId(userId);
        userWorks.setStatus(UserWorksStatus.RELEASE.real());
        userWorks.setAuditRecordId(0);
        userWorks.setAuditStatus(UserWorksAuditStatus.WAITAUDIT.real());
        userWorks.setDeleted(NOT_DELETED);
        userWorks.setCreateUser(createUser);
        userWorks.setCreateTime(Date.from(Instant.now()));
        userWorks.setUpdateUser(createUser);
        userWorks.setUpdateTime(Date.from(Instant.now()));

        dao.insert(userWorks);
        // 添加视频作品
        UserWorksVideo userWorksVideo
                = userWorksVideoManager.addUserWorksVideo(userWorks, addUserWorksVideoDTO, userId, createUser);
        // 处理作品购物
        List<UserWorksShopping> shoppingList = userWorksShoppingManager.updateUserWorksShopping(userWorks,
                addUserWorksVideoDTO.getStorageId(),
                addUserWorksVideoDTO.getAddUserWorksShoppingsDTOList(),
                createUser);
        // 创建作品计数基础数据
        userWorksStatisticalManager.add(userWorks.getWorksId(), createUser);
        // 审核申请
        userWorksAuditManager.applyVideo(userWorks, userWorksVideo, shoppingList);
        return userWorks;
    }

    /**
     * 添加作品
     *
     * @param addUserWorksDTO
     * @param addUserWorksOpusDTO
     * @param userId
     * @param createUser
     * @return
     */
    @Transactional
    public UserWorks addUserWorksOpus(AddUserWorksDTO addUserWorksDTO, AddUserWorksOpusDTO addUserWorksOpusDTO, Integer userId, String createUser) {
        verify(addUserWorksDTO);

        UserWorks userWorks = new UserWorks();
        userWorks.setCoverImage(addUserWorksDTO.getCoverImage());
        userWorks.setTitle(addUserWorksDTO.getTitle());
        userWorks.setWorksType(UserWorksType.OPUS.real());
        userWorks.setUserId(userId);
        userWorks.setStatus(UserWorksStatus.EDIT.real());
        userWorks.setAuditRecordId(0);
        userWorks.setAuditStatus(UserWorksAuditStatus.WAITAUDIT.real());
        userWorks.setDeleted(NOT_DELETED);
        userWorks.setCreateUser(createUser);
        userWorks.setCreateTime(Date.from(Instant.now()));
        userWorks.setUpdateUser(createUser);
        userWorks.setUpdateTime(Date.from(Instant.now()));

        dao.insert(userWorks);
        // 添加分享图片
        shareImageManager.addShareImage(userWorks.getCoverImage());
        // 添加作品及栏目
        userWorksOpusManager.addUserWorksOpus(userWorks, addUserWorksOpusDTO, userId, createUser);
        // 创建作品计数基础数据
        userWorksStatisticalManager.add(userWorks.getWorksId(), createUser);
        return userWorks;
    }

    /**
     * 发布作品
     *
     * @param record
     * @param updateUser
     */
    @Transactional
    public boolean releaseUserWorks(UserWorks record, String updateUser) {
        record.setStatus(UserWorksStatus.RELEASE.real());
        record.setUpdateUser(updateUser);
        record.setUpdateTime(Date.from(Instant.now()));
        dao.updateByPrimaryKeySelective(record, Column.status, Column.updateUser, Column.updateTime);

        UserWorksOpus userWorksOpus = userWorksOpusManager.getByWorksId(record.getWorksId());
        List<UserWorksOpusItems> opusItemList = userWorksOpusItemsManager.getByWorksId(record.getWorksId());
        List<UserWorksShopping> shoppingList = userWorksShoppingManager.queryByWorksId(record.getWorksId());
        // 审核申请
        userWorksAuditManager.applyOpus(record, userWorksOpus, opusItemList, shoppingList);

        return true;
    }

    /**
     * 编辑图文灵感辑
     *
     * @param userWorks
     * @param editUserWorksImageDTO
     * @param userId
     * @param updateUser
     * @return
     */
    @Transactional
    public UserWorks editUserWorksImages(UserWorks userWorks, EditUserWorksImageDTO editUserWorksImageDTO, Integer userId, String updateUser) {
        // userWorks.setUpdateUser(updateUser);
        // userWorks.setUpdateTime(Date.from(Instant.now()));
        // // TODO 进入审核流程
        // userWorks.setAuditStatus(UserWorksAuditStatus.PASS.real());
        // dao.updateByPrimaryKeySelective(userWorks,
        // Column.excludes(Column.deleted, Column.createUser, Column.createTime));
        //
        // // 更新图文作品
        // userWorksImagesManager.editUserWorksImages(userWorks, editUserWorksImageDTO, updateUser);
        return userWorks;
    }

    /**
     * 编辑视频灵感辑
     *
     * @param userWorks
     * @param editUserWorksVideoDTO
     * @param userId
     * @param updateUser
     * @return
     */
    @Transactional
    public UserWorks editUserWorksVideo(UserWorks userWorks, EditUserWorksVideoDTO editUserWorksVideoDTO, Integer userId, String updateUser) {
        // userWorks.setUpdateUser(updateUser);
        // userWorks.setUpdateTime(Date.from(Instant.now()));
        // // TODO 进入审核流程
        // userWorks.setAuditStatus(UserWorksAuditStatus.PASS.real());
        // dao.updateByPrimaryKeySelective(userWorks,
        // Column.excludes(Column.deleted, Column.createUser, Column.createTime));
        //
        // // 更新视频作品
        // userWorksVideoManager.editUserWorksVideo(userWorks, editUserWorksVideoDTO, updateUser);
        return userWorks;
    }

    /**
     * 给作品设置审核记录Id
     *
     * @param userWorks
     * @param auditRecordId
     * @param updateUser
     */
    public void settingAuditRecordId(UserWorks userWorks, Integer auditRecordId, String updateUser) {
        userWorks.setAuditRecordId(auditRecordId);
        userWorks.setUpdateUser(updateUser);
        userWorks.setUpdateTime(Date.from(Instant.now()));
        dao.updateByPrimaryKeySelective(userWorks, Column.auditRecordId, Column.updateUser, Column.updateTime);
    }

    /**
     * 根据作品Id和审核Id获取作品
     *
     * @param worksId
     * @param auditRecordId
     * @return
     */
    public UserWorks getByWorksIdAndAuditRecordId(Integer worksId, Integer auditRecordId) {
        UserWorksExample example = new UserWorksExample();
        example.createCriteria().andWorksIdEqualTo(worksId).andAuditRecordIdEqualTo(auditRecordId).andDeletedEqualTo(
                NOT_DELETED);
        return dao.selectOneByExample(example);
    }

    /**
     * 重置审核状态
     *
     * @param userWorks
     * @param auditStatus
     * @param updateUser
     */
    public boolean resetAuditStatus(UserWorks userWorks, UserWorksAuditStatus auditStatus, String updateUser) {
        // 条件
        UserWorksExample example = new UserWorksExample();
        example.createCriteria().andWorksIdEqualTo(userWorks.getWorksId())
                // 必须审核记录与数据是一致的
                .andAuditRecordIdEqualTo(userWorks.getAuditRecordId()).andDeletedEqualTo(NOT_DELETED);

        userWorks.setAuditStatus(auditStatus.real());

        return dao.updateByExampleSelective(userWorks,
                example,
                Column.auditStatus,
                Column.updateUser,
                Column.updateTime) == 1;
    }

    /**
     * 编辑作品
     *
     * @param userWorks
     * @param editUserWorksOpusDTO
     * @param userId
     * @param updateUser
     * @return
     */
    @Transactional
    public UserWorks editUserWorksOpus(UserWorks userWorks, EditUserWorksOpusDTO editUserWorksOpusDTO, Integer userId, String updateUser) {
        userWorks.setUserId(userId);
        userWorks.setStatus(UserWorksStatus.EDIT.real());
        userWorks.setAuditRecordId(0);
        userWorks.setAuditStatus(UserWorksAuditStatus.WAITAUDIT.real());
        userWorks.setUpdateUser(updateUser);
        userWorks.setUpdateTime(Date.from(Instant.now()));
        dao.updateByPrimaryKeySelective(userWorks, Column.excludes(Column.createUser, Column.createTime));

        // 更新作品及栏目
        userWorksOpusManager.editUserWorksOpus(userWorks, editUserWorksOpusDTO, userId, updateUser);
        return userWorks;
    }

    @Transactional
    public void deleteUserWorksImages(UserWorks userWorks, String updateUser) {
        userWorks.setDeleted(UserWorks.IS_DELETED);
        userWorks.setUpdateUser(updateUser);
        userWorks.setUpdateTime(Date.from(Instant.now()));
        dao.updateByPrimaryKeySelective(userWorks, Column.deleted, Column.updateUser, Column.updateTime);
        // 删除图文作品
        userWorksImagesManager.delete(userWorks, updateUser);
    }

    @Transactional
    public void deleteUserWorksVideo(UserWorks userWorks, String updateUser) {
        userWorks.setDeleted(UserWorks.IS_DELETED);
        userWorks.setUpdateUser(updateUser);
        userWorks.setUpdateTime(Date.from(Instant.now()));
        dao.updateByPrimaryKeySelective(userWorks, Column.deleted, Column.updateUser, Column.updateTime);
        // 删除视频信息
        userWorksVideoManager.delete(userWorks, updateUser);
    }

    @Transactional
    public void deleteUserWorksOpus(UserWorks userWorks, String updateUser) {
        userWorks.setDeleted(UserWorks.IS_DELETED);
        userWorks.setUpdateUser(updateUser);
        userWorks.setUpdateTime(Date.from(Instant.now()));
        dao.updateByPrimaryKeySelective(userWorks, Column.deleted, Column.updateUser, Column.updateTime);
        // 删除作品及栏目等信息
        userWorksOpusManager.delete(userWorks, updateUser);
    }

    public List<UserWorks> queryByWorksIds(List<Integer> worksIdList) {
        UserWorksExample example = new UserWorksExample();
        Criteria criteria = example.createCriteria();
        criteria.andWorksIdIn(worksIdList)
                .andDeletedEqualTo(NOT_DELETED)
                .andStatusEqualTo(UserWorksStatus.RELEASE.real())
                .andAuditStatusEqualTo(UserWorksAuditStatus.PASS.real());

        return dao.selectByExample(example);
    }

    /**
     * 根据商品Id查询关联的作品列表
     * @param outsourcingGoodsId
     * @param size
     * @return
     */
    public List<UserWorks> listByOutsourcinggoodsId(Integer outsourcingGoodsId,Integer size){
    	return dao.listByOutsourcinggoodsId(outsourcingGoodsId, size);
    }
    
    public Pagination<UserWorks> queryByOutsourcinggoodsId(Integer outsourcingGoodsId,Page page){
    	return Pagination.create(page, 
    		dao.countByOutsourcinggoodsId(outsourcingGoodsId),
    		() -> dao.queryByOutsourcinggoodsId(outsourcingGoodsId, page));
    }
}